package com.kid.keep.service.impl;

import cn.hutool.core.lang.Assert;
import com.kid.keep.constant.PathConstant;
import com.kid.keep.dao.app.AppRepository;
import com.kid.keep.dao.user.UserRepository;
import com.kid.keep.dto.AddUserDTO;
import com.kid.keep.dto.UserDTO;
import com.kid.keep.enums.BizExceptionEnum;
import com.kid.keep.enums.DateStatusEnum;
import com.kid.keep.exception.BizException;
import com.kid.keep.mapper.IUserCovertMapper;
import com.kid.keep.po.App;
import com.kid.keep.po.User;
import com.kid.keep.response.Code2SessionResponse;
import com.kid.keep.service.IUserService;
import com.honeybee.cloud.framework.common.idwork.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Objects;

/**
 * @Description 用户相关操作
 * @Author JOHN
 * @Create 2020-01-02
 * @Since 1.0.0
 */
@Service
@Slf4j
public class UserService implements IUserService {
    private UserRepository userRepository;

    private AppRepository appRepository;
    private IUserCovertMapper userCovertMapper;
    private IdWorker idWorker;
    private RestTemplate restTemplate;

    @Autowired
    public void setUserCovertMapper(IUserCovertMapper userCovertMapper) {
        this.userCovertMapper = userCovertMapper;
    }

    @Autowired
    public void setIdWorker(IdWorker idWorker) {
        this.idWorker = idWorker;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    public UserService(UserRepository userRepository, AppRepository appRepository) {
        this.userRepository = userRepository;
        this.appRepository = appRepository;
    }

    @Override
    public UserDTO addUser(AddUserDTO addUserDTO) {
        Assert.notNull(addUserDTO, "request param is null");
        Assert.notNull(addUserDTO.getCode(), "code is null");
        App app=appRepository.findByWxAppIdAndDataStatus(addUserDTO.getAppId(), DateStatusEnum.VALID.getValue());
        if(Objects.isNull(app)){
            throw BizException.getInstance(BizExceptionEnum.LOGIN_INVALID);
        }
        String openId = getOpenId(addUserDTO.getCode());
        User user = userCovertMapper.toPO(addUserDTO, new Date(), openId,app.getId());
        User existUser = userRepository.findByOpenIdAndAppId(user.getOpenId(),app.getId());
        if (Objects.nonNull(existUser)) {
            user.setId(existUser.getId());
            userRepository.updateById(user);
        } else {
            user.setId(idWorker.nextId());
            userRepository.save(user);
        }
        return userCovertMapper.toDTO(user);
    }

    @Override
    public UserDTO findByIdAndAppId(Long userId, Long appId) {
        User user = userRepository.findByIdAndAppId(userId, appId);
        return userCovertMapper.toDTO(user);
    }

    @Override
    public UserDTO findById(Long userId) {
        User user = userRepository.findById(userId);
        return userCovertMapper.toDTO(user);
    }

    private String getOpenId(String code) {
        try {
            Code2SessionResponse response = restTemplate.getForObject(PathConstant.CODE_2_SESSION_URL, Code2SessionResponse.class, PathConstant.APP_ID, PathConstant.APP_SECRET, code);
            if (Objects.isNull(response) || StringUtils.isBlank(response.getOpenId())) {
                throw BizException.getInstance(BizExceptionEnum.LOGIN_INVALID);
            }
            return response.getOpenId();
        } catch (Exception e) {
            log.error("获取openId异常", e);
            throw BizException.getInstance(BizExceptionEnum.LOGIN_INVALID);
        }

    }
}
